{{- define "validating.webhook.config" }}
admissionReviewVersions:
  - v1
clientConfig:
  caBundle: {{ .Values.admissionPolicyEngine.internal.webhook.ca | b64enc | quote }}
  service:
    name: gatekeeper-webhook-service
    namespace: d8-admission-policy-engine
    path: /v1/admit
failurePolicy: Ignore
matchPolicy: Exact
sideEffects: None
objectSelector: {}
{{- end }}

{{- define "validating.webhook.tracked.resources"}}
  {{- range $trackResource := .Values.admissionPolicyEngine.internal.trackedConstraintResources }}
- apiGroups:
    {{- $trackResource.apiGroups | toYaml | nindent 4 }}
  apiVersions:
  - '*'
  operations:
  - CREATE
  - UPDATE
  resources:
    {{- $trackResource.resources | toYaml | nindent 4 }}
  {{- end }}
{{- end }}

{{- if .Values.admissionPolicyEngine.internal.bootstrapped }}
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: d8-admission-policy-engine-config
  {{- include "helm_lib_module_labels" (list . (dict "app" "gatekeeper" "control-plane" "controller-manager" "gatekeeper.sh/system" "yes")) | nindent 2 }}
webhooks:
  {{- if include "trivy.provider.enabled" . }}
- name: trivy-provider.deckhouse.io
  namespaceSelector:
    matchLabels:
      security.deckhouse.io/trivy-provider: ""
  rules:
  - apiGroups: ["apps"]
    resources: ["deployments", "daemonsets", "statefulsets"]
    apiVersions: ["*"]
    operations: ["CREATE", "UPDATE"]
  - apiGroups: ["apps.kruise.io"]
    apiVersions: ["*"]
    resources: ["daemonsets"]
    operations: ["CREATE", "UPDATE"]
  - apiGroups: [""]
    apiVersions: ["*"]
    resources: ["pods"]
    operations: ["CREATE"]

  {{/* Include tracked resources because in the next webhook there is exception for namespaces with 'security.deckhouse.io/trivy-provider' label */}}
  {{- include "validating.webhook.tracked.resources" . | nindent 2 }}

  {{/* Increase timeout for trivy-provider */}}
  timeoutSeconds: 30

  {{- include "validating.webhook.config" . | nindent 2 }}
  {{- end }}

  {{- if (gt (len .Values.admissionPolicyEngine.internal.trackedConstraintResources) 0) }}
- name: admission-policy-engine.deckhouse.io
  namespaceSelector:
    matchExpressions:
    - key: heritage
      operator: NotIn
      values:
        - deckhouse
    - key: security.deckhouse.io/trivy-provider
      operator: DoesNotExist
  rules:
  {{- include "validating.webhook.tracked.resources" . | nindent 2 }}
  timeoutSeconds: 3
  {{- include "validating.webhook.config" . | nindent 2 }}
  {{- end }}
{{- end }}
